package com.hsd.znsh.service;

import com.hsd.znsh.entity.SensorData;
import com.hsd.znsh.repository.SensorDataRepository;
import com.hsd.znsh.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.util.concurrent.ListenableFuture;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CountDownLatch;

/*
 * @auther: wangjiacai
 *
 * @create: 2018-06-25 15:07:02
 */
@Service
public class AsyncService {

    @Autowired
    private SensorDataRepository sensorDataRepository;

    @Async
    public ListenableFuture<List<SensorData>> findSensorDataByTimeBetween(String sensorSn, Integer propertyId,
                                                                          LocalDateTime start, LocalDateTime end, Integer interval){
        List<SensorData> list=sensorDataRepository.findBySensorSnAndTimeBetweenAndPropertyIdOrderByTimeAsc(sensorSn,
                DateUtil.localDateTimeToDate(start),DateUtil.localDateTimeToDate(end),propertyId);
        /*while(start.isBefore(end)) {
            date= DateUtil.localDateTimeToDate(start);
            sensorData=findFirstSensorDataByTimeGreaterThanEqual(sensorSn,date,propertyId);
            if(sensorData!=null) list.add(sensorData);
            start=start.plusMinutes(interval);
        }*/
        int i=0;
        for(int j=0;j<list.size();j++){
            SensorData sensorData=list.get(j);
            LocalDateTime time=DateUtil.dateToLocalDateTime(sensorData.getTime());
            if(start.isAfter(time)){
                list.remove(j--);
            }else{
                i++;
                start=time.plusMinutes(interval);
            }

        }
        return new AsyncResult<>(list);
    }

    public SensorData findFirstSensorDataByTimeGreaterThanEqual(String sensorSn, Date date, Integer propertyId){
        PageRequest pageRequest=new PageRequest(0,1);
        List<SensorData> list=sensorDataRepository.findBySensorSnAndTimeGreaterThanEqualAndPropertyIdOrderByTimeAsc(
                sensorSn,date,propertyId,pageRequest);
        if(list.size()>0) return list.get(0);
        return null;
    }


}

